package com.ht.api.controller;

import java.util.List;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ht.api.bean.AjaxResult;
import com.ht.api.call.ICall;
import com.ht.api.call.func.IFunctionCall;
import com.ht.api.db.Db;
import com.ht.api.db.DbList;
import com.ht.api.db.DbPage;
import com.ht.api.db.exception.HtException;
import com.ht.api.db.util.FunctionUtil;
import com.ht.api.util.UserUtil;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * 一些特殊的接口（通用接口不方便实现的）
 * @author asq
 * @createTime 2025年1月1日 13:21:29
 */
@RestController
@RequestMapping("/custom")
public class CustomController {
	
	/**
	 * 查询菜单关联的所有接口
	 * @param menuId 菜单ID
	 * @return
	 */
	@PostMapping("menu-call-list")
	public AjaxResult getMenuCallList(@RequestBody JSONObject body) {
		// 解析参数
		long menuId = 0;
		try {
			menuId = body.getByPath("param.menu_id", Long.class);
		} catch (Exception e) {
			throw new HtException("json参数格式不正确~");
		}
		
		// 查询
		String s = "select c.*,mc.main_id rel_id from call c inner join sys_menu_call mc on c.main_id=mc.call_id "
				+ "where c.sys_deleted=1 and mc.sys_deleted=1 and mc.menu_id=?";
		DbList dbList = Db.query(s, menuId);
		
		// 构造分页对象
		DbPage dbPage = DbPage.builder().record(dbList).build();
		
		return AjaxResult.success().put(ICall.DATA, dbPage);
	}
	
	/**
	 * 查询前置/后置函数列表
	 * @return
	 */
	@PostMapping("func-list")
	public AjaxResult getFunctionList() {
		List<IFunctionCall> functionList = FunctionUtil.getFunctionsByType(IFunctionCall.class);
		List<JSONObject> list = functionList.stream().map(c -> {
			JSONObject bean = JSONUtil.createObj();
			bean.set("key", c.getClass().getSimpleName());
			bean.set("label", c.getName());
			return bean;
		}).toList();
		
		return AjaxResult.success().put(ICall.DATA, list);
	}
	
	//查询登陆用户详情
	@PostMapping("/get-user-info")
	public AjaxResult getLoginInfo() {
		long uid = UserUtil.getLoginUser().getId();
		return AjaxResult.success(Db.createSqlParser("sys_user").findById(uid));
	}
}
